<template>
  <div class="student-detail">
    <div class="page-header">
      <el-button @click="$router.back()" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2 class="page-title">学生详情</h2>
      <el-button type="primary" @click="editStudent">
        <el-icon><Edit /></el-icon>
        编辑
      </el-button>
    </div>

    <div v-if="studentStore.loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <div v-else-if="student" class="student-content">
      <!-- 基本信息卡片 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><User /></el-icon>
            <span>基本信息</span>
          </div>
        </template>
        
        <div class="student-info">
          <div class="avatar-section">
            <el-avatar :size="100" :src="student.avatar || '/default-avatar.png'">
              {{ student.name?.[0] }}
            </el-avatar>
            <div class="basic-info">
              <h3>{{ student.name }}</h3>
              <p class="student-id">学号：{{ student.student_id }}</p>
              <el-tag :type="student.gender === '男' ? 'primary' : 'danger'" size="large">
                {{ student.gender }}
              </el-tag>
            </div>
          </div>
          
          <el-row :gutter="20" class="details-row">
            <el-col :xs="24" :sm="12" :md="8">
              <div class="detail-item">
                <div class="label">年龄</div>
                <div class="value">{{ student.age }}岁</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <div class="detail-item">
                <div class="label">班级</div>
                <div class="value">{{ student.class_name }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <div class="detail-item">
                <div class="label">入学年份</div>
                <div class="value">{{ student.enrollment_year || '2023' }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 联系信息卡片 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><Phone /></el-icon>
            <span>联系信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <div class="detail-item">
              <div class="label">联系电话</div>
              <div class="value">
                <el-link :href="`tel:${student.phone}`" type="primary">
                  {{ student.phone }}
                </el-link>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12">
            <div class="detail-item">
              <div class="label">邮箱地址</div>
              <div class="value">
                <el-link :href="`mailto:${student.email}`" type="primary">
                  {{ student.email }}
                </el-link>
              </div>
            </div>
          </el-col>
          <el-col :xs="24">
            <div class="detail-item">
              <div class="label">家庭地址</div>
              <div class="value">{{ student.address || '暂无' }}</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 成绩信息卡片 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><Postcard /></el-icon>
            <span>成绩信息</span>
          </div>
        </template>
        
        <el-table :data="mockGrades" stripe class="grades-table">
          <el-table-column prop="course_name" label="课程名称" />
          <el-table-column prop="score" label="成绩" width="80">
            <template #default="{ row }">
              <el-tag :type="getScoreType(row.score)">
                {{ row.score }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="credit" label="学分" width="80" />
          <el-table-column prop="semester" label="学期" width="100" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.score >= 60 ? 'success' : 'danger'" size="small">
                {{ row.score >= 60 ? '及格' : '不及格' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="grade-summary">
          <el-statistic
            title="平均分"
            :value="averageScore"
            :precision="1"
            suffix="分"
          />
          <el-statistic
            title="总学分"
            :value="totalCredits"
            suffix="分"
          />
          <el-statistic
            title="及格率"
            :value="passRate"
            :precision="1"
            suffix="%"
          />
        </div>
      </el-card>
    </div>

    <div v-else class="not-found">
      <el-empty description="学生信息不存在" />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑学生信息"
      v-model="showEditDialog"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">更新</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useStudentStore } from '../stores/student'

const props = defineProps({
  id: String
})

const route = useRoute()
const router = useRouter()
const studentStore = useStudentStore()

const showEditDialog = ref(false)
const editFormRef = ref()

// 学生信息
const student = computed(() => studentStore.currentStudent)

// 模拟成绩数据
const mockGrades = ref([
  { course_name: '高等数学', score: 85, credit: 4, semester: '2023-1' },
  { course_name: '程序设计基础', score: 92, credit: 3, semester: '2023-1' },
  { course_name: '数据结构', score: 78, credit: 3, semester: '2023-2' },
  { course_name: '数据库原理', score: 88, credit: 3, semester: '2023-2' },
  { course_name: '计算机网络', score: 76, credit: 3, semester: '2024-1' }
])

// 编辑表单
const editForm = reactive({
  name: '',
  phone: '',
  email: '',
  address: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 计算属性
const averageScore = computed(() => {
  if (mockGrades.value.length === 0) return 0
  const total = mockGrades.value.reduce((sum, grade) => sum + grade.score, 0)
  return total / mockGrades.value.length
})

const totalCredits = computed(() => {
  return mockGrades.value.reduce((sum, grade) => sum + grade.credit, 0)
})

const passRate = computed(() => {
  if (mockGrades.value.length === 0) return 0
  const passCount = mockGrades.value.filter(grade => grade.score >= 60).length
  return (passCount / mockGrades.value.length) * 100
})

// 方法
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'primary'
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

const editStudent = () => {
  if (student.value) {
    Object.assign(editForm, {
      name: student.value.name,
      phone: student.value.phone,
      email: student.value.email,
      address: student.value.address
    })
    showEditDialog.value = true
  }
}

const handleUpdate = async () => {
  try {
    await editFormRef.value.validate()
    await studentStore.updateStudent(props.id || route.params.id, editForm)
    ElMessage.success('更新成功')
    showEditDialog.value = false
    // 重新获取学生信息
    await studentStore.fetchStudentById(props.id || route.params.id)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('更新失败')
    }
  }
}

const resetForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 生命周期
onMounted(async () => {
  const studentId = props.id || route.params.id
  if (studentId) {
    try {
      await studentStore.fetchStudentById(studentId)
    } catch (error) {
      ElMessage.error('获取学生信息失败')
    }
  }
})
</script>

<style scoped>
.student-detail {
  padding: 0;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 10px;
}

.back-btn {
  margin-right: auto;
}

.page-title {
  margin: 0;
  color: #303133;
  font-weight: 500;
  flex: 1;
  text-align: center;
}

.loading-container {
  margin-top: 20px;
}

.student-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.student-info {
  padding: 10px 0;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.basic-info h3 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.student-id {
  margin: 0 0 10px 0;
  color: #909399;
  font-size: 14px;
}

.details-row {
  margin-top: 20px;
}

.detail-item {
  margin-bottom: 15px;
}

.label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.grades-table {
  margin-bottom: 20px;
}

.grade-summary {
  display: flex;
  justify-content: space-around;
  background: #f5f7fa;
  padding: 20px;
  border-radius: 6px;
}

.not-found {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .back-btn {
    margin-right: 0;
    align-self: flex-start;
  }
  
  .page-title {
    text-align: left;
    margin: 10px 0;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }
  
  .grade-summary {
    flex-direction: column;
    gap: 15px;
  }
  
  .details-row .el-col {
    margin-bottom: 10px;
  }
}
</style> 